#coding=utf-8

import logging
import functools
from google.appengine.api import users
from google.appengine.api import memcache
import datetime
import unicodedata
import tornado.web
import tornado.escape
from models import *
from utils import page
from lib import markdown
import constants

class BaseController(tornado.web.RequestHandler):
    def get_current_account(self):
        anonymous_user_email = "anonymous@gmail.com"
        user = users.get_current_user()
        if user is None:
            user = users.User(anonymous_user_email)
        account = memcache.get(user.email())
        if account is None:
            account = Account.get_account_for_user(user)
            memcache.set(user.email(), account)
        return account

    def render_response_string(self, template_name, **kwargs):
        user = self.get_current_account()
        sign_in_url = users.create_login_url(self.request.uri)
        sign_out_url = users.create_logout_url(self.request.uri) 
        # Let the templates access the users module to generate login URLs
        return tornado.web.RequestHandler.render_string(
            self, template_name,
            user=user,
            sign_in_url=sign_in_url,
            sign_out_url=sign_out_url,
            **kwargs)
    
    def render_response(self, template_name, **kwargs):
        user = self.get_current_account()
        sign_in_url = users.create_login_url(self.request.uri)
        sign_out_url = users.create_logout_url(self.request.uri) 
        self.render(template_name,
                    user=user,
                    sign_in_url=sign_in_url,
                    sign_out_url=sign_out_url, 
                    **kwargs)
    
    def render_json(self, val):
        self.write(tornado.escape.json_encode(val))
    
    def get_error_html(self, status_code):
        if status_code == 404 or status_code == 403:
            msg = '抱歉，所访问的资源不存在。'
        else:
            msg = '抱歉，所访问的资源不存在。'
        return self.render_string('error.html', error_msg=msg)

### Decorators for request handlers ###
def login_required(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not users.get_current_user():
            if self.request.method == "GET":
                self.redirect(users.create_login_url(self.request.uri))
                return
            raise tornado.web.HTTPError(403)
        else:
            return method(self, *args, **kwargs)
    return wrapper

def admin_required(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not users.get_current_user():
            if self.request.method == "GET":
                self.redirect(users.create_login_url(self.request.uri))
                return
            raise tornado.web.HTTPError(403)
        elif not users.is_current_user_admin():
            if self.request.method == "GET":
                self.redirect("/")
                return
            raise tornado.web.HTTPError(403)
        else:
            return method(self, *args, **kwargs)
    return wrapper

############## controllers  ############
class HomeController(BaseController):
    def get(self):
        self.render_response('home.html')

class CalController(BaseController):
    def get(self):
        sefl.render_response('lunarbirthday.html')
    def post(self):
        cal_info = CalInfo()
        cal_info.summary = self.get_argument('summary', '')
        cal_info.lunar_birthday_str = self.get_argument('birthday')
        cal_info.start_year = int(self.get_argument('startYear'))
        cal_info.end_year = int(self.get_argument('endYear'))
        cal_info.location = self.get_argument('location', '')
        cal_info.description = self.get_argument('description', '')
        ics_str = cal_info.create_cal_ics();
        filename = 'birthday.ics'
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=%s' % filename.encode('utf8'))
        self.write(ics_str)

class ReaderSharedFeedController(BaseController):
    def get(self):
        pass
    def post(self):
        rsf = ReaderSharedFeed()
        rsf.feed_url         = self.get_argument('feedUrl')
        rsf.feed_owner_id    = self.get_argument('feedOwnerId', None)
        rsf.feed_owner_email = self.get_argument('feedOwnerEmail')
        rsf.save()
        self.render_json({'msg' : 'OK'});
        
        